/**
 * 四条边界：top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1
 * left -> right 方向遍历顶层，res.push(matrix[top][i]) 顶层元从左至右素依次加入 res，遍历完成后 top++
 * top -> bottom 方向遍历右层，res.push(matrix[i][right]) 右层元素从上至下依次加入 res，遍历完成后 right--
 * right -> left 方向遍历底层，res.push(matrix[bottom][i]) 底层元从右至左素依次加入 res，遍历完成后 bottom--
 * bottom -> top 方向遍历左层，res.push(matrix[i][left]) 左层元素从下至上依次加入 res，遍历完成后 left++
 * @param {number[][]} matrix
 * @return {number[]}
 */
const spiralOrder = matrix => {
  if (!matrix.length || !matrix[0].length) return []

  const res = []
  let top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1

  while (top <= bottom && left <= right) {
    for (let i = left; i <= right; i++) {
      res.push(matrix[top][i])
    }
    top += 1
    for (let i = top; i <= bottom; i++) {
      res.push(matrix[i][right])
    }
    right -= 1
    if (top > bottom || left > right) {
      break
    }
    for (let i = right; i >= left; i--) {
      res.push(matrix[bottom][i])
    }
    bottom -= 1
    for (let i = bottom; i >= top; i--) {
      res.push(matrix[i][left])
    }
    left += 1
  }
  return res
}

console.log(spiralOrder([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))